package com.my.algorithmlearning.leetcode;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * @ClassName Medium_48_Rotate2DImage
 * @Description Medium_48_Rotate2DImage
 * @Author wanghaiwei
 * @Date 2023/2/23 17:06
 */
public class Medium_48_Rotate2DImage {
    public void rotate(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return;
        }
        rotateOfLevel(0, matrix);
    }

    private void rotateOfLevel(int rounds, int[][] matrix) {
        if (rounds == (matrix.length / 2)) {
            return;
        }
        int currRoundsLength = matrix.length - 2 * rounds;
        int currRoundsStart = rounds;
        int currRoundsEnd = rounds + currRoundsLength - 1;
        int r = currRoundsStart;
        int c = currRoundsStart;
        for (int i = 0; i < currRoundsLength - 1; i++, c++) {
            swap(matrix, r, c, r + i, currRoundsEnd);
            swap(matrix, r, c, currRoundsEnd, r + currRoundsLength - 1 - i);
            swap(matrix, r, c, r + currRoundsLength - 1 - i, currRoundsStart);
        }
        rotateOfLevel(rounds + 1, matrix);
    }

    private void swap(int[][] matrix, int r1, int c1, int r2, int c2) {
        int tmp = matrix[r1][c1];
        matrix[r1][c1] = matrix[r2][c2];
        matrix[r2][c2] = tmp;
    }

    public static void main(String[] args) {
        Medium_48_Rotate2DImage solution = new Medium_48_Rotate2DImage();
        int[][] input = new int[][]{{5, 1, 9, 11}, {2, 4, 8, 10}, {13, 3, 6, 7}, {15, 14, 12, 16}};
        solution.rotate(input);
        String resultStr = Arrays.stream(input).map(r -> "[" + StringUtils.join(r, ',') + "]").collect(Collectors.joining(","));
        Assert.isTrue("[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]".equals(resultStr), "matrix = [5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]计算错误，预期：[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]， 实际：" + resultStr);
    }
}
